<?php

namespace common\jobs\handle;

use Yii;
use yii\base\Exception;
use common\models\plugin\PluginPrize;
use common\models\plugin\PluginRewardLog;
use common\models\sghome\Unions;
use common\models\sghome\UserAccount;
use common\models\sghome\UserAccountLogs;
use common\helpers\IpHelper;

/**
 * 插件奖励任务处理
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class PluginRewardHandle extends \common\jobs\base\BaseJobHandleModel {

    /**
     * @var integer 插件奖励日志ID
     */
    public $log_id = null;

    /**
     * @var PluginRewardLog|null 模型
     */
    private $_model = null;

    /**
     * @var PluginPrize|null 模型
     */
    private $_prize = null;

    /**
     * @var Unions|null 模型
     */
    private $_union = null;

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['log_id'], 'required'],
            [['log_id'], 'integer'],
            [['log_id'], 'validateLog'],
        ];
    }

    /**
     * 校验奖励日志信息
     * @param string $attribute the attribute currently being validated
     */
    public function validateLog($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $model = PluginRewardLog::find()->active()->andWhere([
            'id' => $this->$attribute,
            'status' => PluginRewardLog::STATUS_DEFAULT,
        ])->one();
        if (!$model) {
            return $this->addError($attribute, '【' . $this->$attribute . '】奖励日志信息不存在或者已执行奖励！');
        }
        if (!$model->prize) {
            return $this->addError($attribute, '【' . $this->$attribute . '】奖励奖品信息不存在！');
        }
        if ($model->prize->type !== PluginPrize::TYPE_CREDIT) {
            return $this->addError($attribute, '【' . $this->$attribute . '】奖品类型非积分奖品！');
        }
        if (!$model->prize->union) {
            return $this->addError($attribute, '【' . $this->$attribute . '】工会信息不存在！');
        }
        if ($model->prize->union->credits < $model->prize->price) {
            return $this->addError($attribute, '【' . $this->$attribute . '】工会积分不足！');
        }
        $this->_union = $model->prize->union;
        $this->_prize = $model->prize;
        $this->_model = $model;
    }

    /**
     * 获取日志信息
     * @return PluginRewardLog|null
     */
    public function getModel() {
        return $this->_model;
    }

    /**
     * 获取工会信息
     * @return Unions|null
     */
    public function getUnion() {
        return $this->_union;
    }

    /**
     * 获取奖品信息
     * @return PluginPrize|null
     */
    public function getPrize() {
        return $this->_prize;
    }

    /**
     * 执行年票确认
     * @inheritdoc
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('确认检验失败');
        }
        //获取信息
        $log = $this->getModel();
        $prize = $this->getPrize();
        $union = $this->getUnion();

        $credit = $prize->price;
        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            //更新工会积分
            $union->credits -= $credit;
            $union->used_credits += $credit;
            if (!$union->save()) {
                throw new Exception('工会积分更新失败');
            }
            //发放奖励积分到用户
            $account = $log->account;
            if (!$account) {
                $account = new UserAccount();
                $account->user_id = $log->user_id;
                $account->credit = 0;
            }
            $account->credit += $credit;
            if (!$account->save()) {
                throw new Exception('用户积分更新失败');
            }
            //写入用户积分日志
            $accountLog = new UserAccountLogs();
            $accountLog->user_id = $log->user_id;
            $accountLog->type = 'credit';
            $accountLog->amount = $credit;
            $accountLog->current = $account->credit;
            $accountLog->mark = Yii::t('message', $prize->getRewardMessageTemplate(), [
                'credit' => $credit
            ]);
            $accountLog->detail = 'PluginRewardLog';
            if ($log->ip) {
                $accountLog->ip = IpHelper::long2ip($log->ip);
            }
            $accountLog->detail_id = $log->id;
            if (!$accountLog->save()) {
                throw new Exception('用户积分日志写入失败');
            }
            //更新插件奖励日志
            $log->status = PluginRewardLog::STATUS_ACTIVE;
            if (!$log->save()) {
                throw new Exception('奖励日志更新失败');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            Yii::error($e->getMessage());
            return $this->dumpRetryError($e->getMessage());
        }

        return $this->dumpSuccess([
            'PluginRewardId' => $log->id,
            'Message' => '奖励发放完成！',
        ]);
    }

    /**
     * @inheritdoc
     */
    protected function pushLog() {
        //推送消息
        $pushMark = sprintf($board->pushMessage, $board->credit);
        Yii::error('[PUSH CONTENT:' . $board->jPushID . ']' . ':' . $pushMark);
        if ($board->jPushID) {
            $logid = Yii::$app->queue->push(new \common\jobs\JPushJob([
                'title' => $pushMark,
                'redirect' => 'sghome://web?link=https://daas.lunengsports.com/m/credits',
                'durtion' => 1,
                'tokens' => [$board->jPushID]
            ]));
            Yii::error('[PUSH Running:' . $board->jPushID . ']' . 'LOG ID:' . $logid);
        } else {
            Yii::error('[PUSH ERROR jPushID NOT EXIST]' . 'UID:' . $board->user_id);
        }
    }

}
